<template>
  <lay-breadcrumb>
    <template v-for="(item, index) in list">
      <lay-breadcrumb-item v-if="item.meta.title" :key="index">
        {{ item.meta.title }}
      </lay-breadcrumb-item>
    </template>
  </lay-breadcrumb>
</template>
<script setup>
  import { ref, onMounted, watch } from "vue";
  import { useRoute } from "vue-router";
  import { getRouteInfo } from "@/utils/getTopToute";
  import { cache } from "@/utils/cache";
  import { deepCopy, inArray } from "@/utils/tool";
  import config from "@/config/index";

  // 获取菜单路由
  const MenuRouteList = cache(config.MenuCacheName);
  // 深度拷贝菜单路由
  const menuTree = deepCopy(MenuRouteList);

  // 获取顶级路由
  const getTopRoute = (path) => {
    const menuTreeList = deepCopy(menuTree);
    var topMmenu = {};
    for (const key in menuTreeList) {
      if (menuTreeList[key]["path"] == path) {
        topMmenu = menuTreeList[key];
        break;
      }
    }
    return topMmenu;
  };

  // 获取最顶级路由信息
  const getTopRouteInfo = (path) => {
    const routeInfo = getRouteInfo(deepCopy(menuTree), path);
    const topRoute = getTopRoute(routeInfo);
    return {
      routeInfo,
      topRoute,
    };
  };

  // 获取子菜单被选中时的父菜单
  const getParentPath = (active_path, topmenu, selected_item) => {
    let parent_item = "";
    for (const key in topmenu) {
      if (
        topmenu[key]["meta"] &&
        topmenu[key]["meta"]["activePath"] &&
        inArray(active_path, topmenu[key]["meta"]["activePath"])
      ) {
        parent_item = topmenu[key];
      }
      if (topmenu[key]["children"] && topmenu[key]["children"].length > 0) {
        selected_item.push(topmenu[key]);
        return getParentPath(active_path, topmenu[key]["children"], selected_item);
      }
    }
    if (parent_item) {
      selected_item.push(parent_item);
    }
    return selected_item;
  };

  var list = ref([]);
  // 面包屑导航
  const route = useRoute();

  let hiddenBreadcrumb = () => {
    // 获取最顶级路由信息
    const topRouteInfo = getTopRouteInfo(route.path);
    // 获取上级名称
    const parent_list = getParentPath(route.path, [topRouteInfo.topRoute], []);
    list.value = [
      ...parent_list,
      {
        path: route.path,
        meta: route.meta,
      },
    ];
  };

  onMounted(() => {
    hiddenBreadcrumb();
  });

  watch(
    () => route.matched,
    () => {
      hiddenBreadcrumb();
    }
  );
</script>
